﻿// =================================================================== 
// 项目说明
//====================================================================
// sushee。@Copy Right 2019
// 文件： SmsCard.cs
// 项目名称：斑马车务
// 创建时间：2019/9/19
// 负责人：sushee
// ===================================================================
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq.Expressions;
using Dapper.Extensions;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Models;
using YouWei.Infrastructure.Repository;
namespace YouWei.Infrastructure.Service
{
	
	/// <summary>
	///短信卡池
	/// </summary>
	public class SmsCardService
	{
         protected SmsCardRepository repository;
        protected SmsMessagePoolRepository repositoryMessage;

        public  SmsCardService(){

            repository = new SmsCardRepository("CarServerConnectionString");
            repositoryMessage =new SmsMessagePoolRepository("CarServerConnectionString");
         }
         
        #region 增删改查

        /// <summary>
        /// 插入
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        public object Insert(SmsCard entity) { return repository.Insert(entity); }

        /// <summary>
        /// 插入
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        public object Insert(List<SmsCard> entitys) { return repository.Insert(entitys); }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        public bool Update(SmsCard entity) { return repository.Update(entity); }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        public bool Delete(SmsCard entity) { return repository.Delete(entity); }

        /// <summary>
        /// 删除所有
        /// </summary>
        /// <returns></returns>
        public bool DeleteAll() { return repository.DeleteAll(); }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="primaryKey">主键</param>
        /// <returns></returns>
        public bool Delete(int primaryKey) { return repository.Delete(primaryKey); }

        /// <summary>
        /// 查询单个实体
        /// </summary>
        /// <param name="primaryKey">主键</param>
        /// <returns></returns>
        public SmsCard SingleOrDefault(object primaryKey) { return repository.SingleOrDefault(primaryKey); }

       
        /// <summary>
        /// 查询单个实体,如果存在多条则引发异常
        /// </summary>
        /// <param name="primaryKey">主键</param>
        /// <returns></returns>
        public SmsCard Single(object primaryKey) { return repository.Single(primaryKey); }

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        public List<SmsCard> QueryAll()
        {
            return repository.QueryAll();
        }

        #endregion


        #region 单表查询帮助方法
        /// <summary>
        /// 根据谓词表达式获取一个对象，如果没有获取到对象，则返回null
        /// </summary>
        /// <param name="predicate">谓词表达式</param>
        /// <param name="useCache">是否使用缓存</param>
        /// <returns></returns>
        public SmsCard QuerySingle(Expression<Func<SmsCard, bool>> predicate, bool useCache = false)
        {
            return QuerySingle(predicate);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="M"></typeparam>
        /// <param name="predicate"></param>
        /// <param name="useCache"></param>
        /// <returns></returns>
        public M QuerySingle<M>(Expression<Func<M, bool>> predicate, bool useCache = false) where M : class
        {
            return repository.QuerySingle<M>(predicate,useCache);
        }
        /// <summary>
        /// 根据谓词表达式获取一个对象列表，如果没有获取到对象，则返回一个空列表
        /// </summary>
        /// <param name="predicate">谓词表达式</param>
        /// <param name="useCache">是否使用缓存</param>
        /// <returns></returns>
        public List<SmsCard> QueryList(Expression<Func<SmsCard, bool>> predicate, bool useCache = false)
        {
            return repository.QueryList(predicate, useCache);
        }
        /// <summary>
        /// 根据谓词表达式获取一个对象列表，如果没有获取到对象，则返回一个空列表
        /// </summary>
        /// <typeparam name="M"></typeparam>
        /// <param name="predicate"></param>
        /// <param name="useCache"></param>
        /// <returns></returns>
        public List<M> QueryList<M>(Expression<Func<M, bool>> predicate, bool useCache = false) where M : class
        {
            return repository.QueryList<M>(predicate, useCache);
        }

        #endregion


        #region 业务逻辑


        /// <summary>
        /// 获取当天所有可用的卡版
        /// </summary>
        /// <param name="dtNowTime"></param>
        /// <returns></returns>
	    public List<SmsCard> GetAllAvaliableCards(DateTime dtNowTime)
	    {
	        return repository.GetAvaliableCards(dtNowTime);
	    }

        /// <summary>
        /// 获取可用卡池
        /// </summary>
        /// <returns></returns>
        public List<SmsCard> GetAvaliableCards(int startTime,int EndTime)
        {
            
            var list= repository.GetAvaliableCards();
            var listReal = new List<SmsCard>();
            foreach (var card in list)
            {
                var nSendCount = repositoryMessage.GetTimeRangeSendCountByMobile(card.OwnerMobile, startTime, EndTime);
                if (nSendCount < card.CountPerDay)
                {
                    listReal.Add(card);
                }
            }
            return listReal;

        }

        /// <summary>
        /// 根据任务ID获取指定时间段内可用卡片
        /// </summary>
        /// <param name="taskID">任务ID</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="EndTime">结束时间</param>
        /// <returns></returns>
        public List<SmsCard> GetAvaliableCards(int taskID,DateTime startTime, DateTime EndTime)
        {

            var list = repository.GetAvaliableCardsByTaskID(taskID);
            var listReal = new List<SmsCard>();
            foreach (var card in list)
            {
                var nSendCount = repositoryMessage.GetTimeRangeSendCountByMobile(card.OwnerMobile, startTime, EndTime);
                if (nSendCount < card.CountPerHour)
                {
                    listReal.Add(card);
                }
            }
            return listReal;

        }

        /// <summary>
        /// 获取可用卡片
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public List<SmsCard> GetAvaliableCards(DateTime startTime, DateTime EndTime)
        {

            var list = repository.GetAvaliableCards();
            var listReal = new List<SmsCard>();
            foreach (var card in list)
            {
                var nSendCount = repositoryMessage.GetTimeRangeSendCountByMobile(card.OwnerMobile, startTime, EndTime);
                if (nSendCount < card.CountPerHour)
                {
                    listReal.Add(card);
                }
            }
            return listReal;

        }

        /// <summary>
        /// 分页查询，带条件
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public Page<SmsCardDto> GetPages(int pageIndex, long pageSize, ReqSmsCardCondition condition)
        {
            return repository.GetPages(pageIndex, pageSize, condition);
        }

        /// <summary>
        /// 手机号是否重复
        /// </summary>
        /// <returns></returns>
        public bool CheckMobile(string tel, int carId)
        {
            return repository.CheckMobile(tel, carId);
        }

        /// <summary>
        /// 批量更新短信卡状态
        /// </summary>
        /// <param name="ids">短信卡ID</param>
        /// <param name="statusType">0:启用 1:禁用</param>
        /// <returns></returns>
        public bool BulkUpdateStatus(List<int> ids, int statusType)
        {
            return repository.BulkUpdateStatus(ids, statusType);
        }
        /// <summary>
        /// 禁用所有卡片
        /// </summary>
	    public void DisabledAllSmsCards()
	    {
	        repository.DisabledAllCards();
	    }


        /// <summary>
        /// 安全地添加卡片
        /// </summary>
        /// <param name="mobile"></param>
	    public void SafeInsertCard(string mobile)
	    {
            var oSmsCard = repository.QuerySingle(m => m.OwnerMobile == mobile);
	        if (oSmsCard == null)
	        {
	            oSmsCard = new SmsCard
	            {
	                OwnerMobile = mobile,
                    CountPerHour = 80,
                    CountPerDay = 500,
	                IsDeleted = 0,
                    CreatedUserID = 1,
                    UpdatedUserID = 1,
                    CreatedTime = DateTime.Now,
                    UpdatedTime = DateTime.Now
	            };
	            repository.Insert(oSmsCard);
	        }
	        else
	        {
	            if (oSmsCard.IsDeleted == 1)
	            {
                    oSmsCard.IsDeleted = 0;
                    oSmsCard.UpdatedTime=DateTime.Now;
                    repository.Update(oSmsCard);
                }
            }
        }
       
        #endregion
    }

}